package com.springbootInit.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springbootInit.backend.common.ErrorCode;
import com.springbootInit.backend.exception.BusinessException;
import com.springbootInit.backend.exception.ThrowUtils;
import com.springbootInit.backend.model.entity.UserInterfaceInfo;
import com.springbootInit.backend.service.UserInterfaceInfoService;
import com.springbootInit.backend.mapper.UserInterfaceInfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
* @author wzhdjy
* @description 针对表【user_interface_info(用户调用接口关系表)】的数据库操作Service实现
* @createDate 2024-01-11 09:52:27
*/
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
    implements UserInterfaceInfoService{


    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {

        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 创建时，参数不能为空
        if (add) {
            if (userInterfaceInfo.getUserId() <= 0 || userInterfaceInfo.getInterfaceInfoId() <= 0){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口或用户不存在");
            }
        }
        // 有参数则校验
        if (userInterfaceInfo.getLeftNum() <= 0) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR,"接口调用次数不足");
        }
    }

    @Override
    public boolean  invokeCount(long interfaceInfoId, long userId) {
        // 校验
        if (interfaceInfoId <= 0 || userId <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UpdateWrapper<UserInterfaceInfo> objectUpdateWrapper = new UpdateWrapper<>();
        // 更新条件
        objectUpdateWrapper.eq("interfaceInfoId",interfaceInfoId).eq("userId",userId);
        objectUpdateWrapper.setSql("totalNum = totalNum + 1 , leftNum = leftNum - 1");
        return this.update(objectUpdateWrapper);
    }
}




